package com.war.demo.service.controller;

import com.war.demo.service.enmu.ApiResponse;
import com.war.demo.service.enmu.ResultCode;
import com.war.demo.service.error.BusinessException;
import com.war.demo.service.util.ApiResponseUtil;
import com.war.demo.service.util.LoggerUtil;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice//定义统一的异常处理类
public class BaseContriller {

    //定义exceptionhandler解决违背controller层吸收的exception
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public ApiResponse handlerException(HttpServletRequest request, Exception ex) {

        ApiResponse rt = new ApiResponse();
        if (ex instanceof BusinessException) {

            BusinessException businessException = (BusinessException) ex;
            System.out.println("BusinessException:" + businessException.getResultCode());
            rt.setResultCode(businessException.getResultCode());
        } else {
            rt.setResultCode(ResultCode.UNKNOW_ERROR);
        }
        LoggerUtil.error("异常信息" + rt.getMessage(), BaseContriller.class);
        return ApiResponseUtil.getResult(rt);
    }
}
